package au.com.handsunited.model.propertyeditors;

import java.beans.PropertyEditorSupport;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author arunda
 *
 */
public class JodaDateTimeEditor extends PropertyEditorSupport {

	private static Logger logger = LoggerFactory.getLogger(JodaDateTimeEditor.class);

	public static final String DATESTR_FORMAT = "yyyyMMdd";
	public static final String TIMESTR_FORMAT = "HHmm";


	/**
	 *
	 */
	public JodaDateTimeEditor() {
		super();
	}

	/**
	 * @param source
	 */
	public JodaDateTimeEditor(Object source) {
		super(source);
	}

	/**
	 * @see java.beans.PropertyEditorSupport#getAsText()
	 */
	@Override
	public String getAsText() {
		if (getSource() == null) {
			return "";
		} else {
			return super.getAsText();
		}
	}

	/**
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {

		DateTimeFormatter fmt = null;

		if (text.length() == DATESTR_FORMAT.length()) {
			fmt = DateTimeFormat.forPattern(DATESTR_FORMAT);
		} else if (text.length() == TIMESTR_FORMAT.length()) {
			fmt = DateTimeFormat.forPattern(TIMESTR_FORMAT);
		}

		DateTime date = fmt.parseDateTime(text);
		setValue(date);
	}

}
